import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import store from "@/store"

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: "/home"
  }, {
    path: '/home',
    name: 'home',
    component: HomeView
  }, {
    path: '/goods',
    name: 'Goods',
    component: () => import('../views/Goods.vue')
  },
  {
    path: '/user',
    name: 'User',
    component: () => import('../views/User.vue'),
    redirect: "/user/cart",
    children: [{
      path: 'cart',
      component: () => import('../components/user/Cart.vue')
    }]
    /*  
       beforeEnter: (to, from, next) => {
           // (只有个人中心进行校验)如果用户没有登录，则不能打开个人中心页面
           let token = localStorage.getItem('x-auth-token');
           if (token) {
             next();
           } else {
             store.dispatch('showToast/asyncIsShowToast', {
               isshow: true,
               msg: "你还没有登录！",
               type: "danger"
             })
           }
         } 
     */
  },
  {
    path: '/order',
    name: 'Order',
    component: () => import('../views/Order.vue')
  },
  {
    path: '/free',
    name: 'Free',
    component: () => import('../views/Free.vue')
  },
  {
    path: "/details",
    name: "Details",
    component: () => import("../views/Detail.vue")
  },
  {
    path: "*",
    name: "error",
    component: () => import("../components/Error.vue")
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 全局前置守卫 : 每次路由切换之前执行了这个钩子
/* 
  to: Route: 即将要进入的目标 路由对象 （准备打开的那个页面）
  from: Route : 当前导航正要离开的路由
  next : Function: 一定要调用该方法来 resolve这个钩子。执行效果以来 next 方法的调用参数
*/
/* 
  router.beforeEach((to, from, next) => {
    if (to.path == "/user") {
      // (只有个人中心进行校验)如果用户没有登录，则不能打开个人中心页面
      let token = localStorage.getItem('x-auth-token');
      if (token) {
        next();
      } else {
        store.dispatch('showToast/asyncIsShowToast', {
          isshow: true,
          msg: "你还没有登录！",
          type: "danger"
        })
      }
    } else {
      next();
    }
  }) 
*/


const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

export default router